﻿var viewModel = new function () {
    $("pagecurrent").removeAttr('disabled');
    //console.log(data);
    this.EmailType = ko.observable("");

    this.ColName = ko.observable("LeadId");
    this.SortOrder = ko.observable("desc");

    //************* PAGING ***************//
    this.ListEmailItems = ko.observableArray();
    this.EmailRecords = ko.observable(this.ListEmailItems().length);
    this.ShowListEmail = ko.observable(false);

    this.CurrentPageIndex = ko.observable(1);
    this.PageSize = ko.observable(10);
    this.MaxPageIndex = ko.computed(function () {
        return Math.ceil(ko.utils.unwrapObservable(this.ListEmailItems().length / this.PageSize()));
    }, this);

    this.itemsOnCurrentPage = ko.computed(function () {
        var pagevalue = this.PageSize().toString().replace(/\s/g, '');
        var pagesize = parseInt(pagevalue, 10);

        if (pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
            return "";
        }
        else {
            var startIndex = this.PageSize() * (this.CurrentPageIndex() - 1);
            var endIndex = parseInt(startIndex) + parseInt(this.PageSize());

            return this.ListEmailItems.slice(startIndex, endIndex);
        }
    }, this);

    this.PageSizeText = ko.computed(function () {
        if (this.ListEmailItems().length > 0) {
            var pagevalue = this.PageSize().toString().replace(/\s/g, '');
            var pagesize = parseInt(pagevalue, 10);
            this.CurrentPageIndex(1);
            if (!IsNumeric(pagevalue))
                return "* Please enter a number between 1 - 100";
            else if (pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
                return "* Please enter a number between 1 - 100";
            }
            else {
                return "";
            }
        }

    }, this);
    this.PageCurrentText = ko.computed(function () {
        if (this.ListEmailItems().length > 0) {
            var pagevalue = this.CurrentPageIndex().toString().replace(/\s/g, '');
            var pageindex = parseInt(pagevalue, 10);
            if (!IsNumeric(this.CurrentPageIndex()) || pagevalue == "")
                return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
            else if (pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > this.MaxPageIndex()) {
                return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
            }
            else {
                return "";
            }
        }
        else {
            return "";
        }

    }, this);

    //************* FILTER ***************//
    this.TemplateOpt = ko.observable("all");
    this.LeadSourceOpt = ko.observable("all");
    this.EmailOpt = ko.observable("all");

    this.AllTemplateOptions = ko.observableArray(data.AllTemplate);
    this.AllLeadSourceOptions = ko.observableArray(data.AllLeadSource);
    this.AllEmailOptions = ko.observableArray(data.AllEmail);

    this.DateSentOptions = ko.observableArray(data.Range);
    this.DateSent = ko.observable(data.Range[7].RangeValue);
    //this.DateSent = ko.observable(data.Range[19].RangeValue);

    this.RangeOption = ko.observable("true");



    // Date Sent Options
    this.RangeEnable = ko.computed(function () {
        if (this.RangeOption() == "true") {
            $("div#selectDataHolder").find(".jcf-unselectable").children("span").css('color', '#000000');
            return true;
        }
        else {
            $("div#selectDataHolder").find(".jcf-unselectable").children("span").css('color', '#464646');
            return false;
        }
    }, this);

    // From, To Options
    this.FromDateEnable = ko.computed(function () {
        return (this.RangeOption() == "false") ? true : false;
    }, this);
    this.ToDateEnable = ko.computed(function () {
        return (this.RangeOption() == "false") ? true : false;
    }, this);

    //************ RESULT *************//
    this.DeliverPercent = ko.observable(FormatPercentOutput(data.DeliverPercent));

    this.RejectPercent = ko.observable(FormatPercentOutput(data.RejectPercent));
    this.SpamPercent = ko.observable(FormatPercentOutput(data.SpamPercent));
    this.hBouncePercent = ko.observable(FormatPercentOutput(data.hBouncePercent));
    this.UnknownUPercent = ko.observable(FormatPercentOutput(data.UnknownUPercent));
    this.sBouncePercent = ko.observable(FormatPercentOutput(data.sBouncePercent));

    this.TotalResults = ko.observable(data.TotalResults);

    this.TotalDelivered = ko.observable(data.TotalDelivered);
    this.TotalRejected = ko.observable(data.TotalRejected);
    this.SpamComplaints = ko.observable(data.SpamComplaints);
    this.HardBounces = ko.observable(data.HardBounces);
    this.UnknownUsers = ko.observable(data.UnknownUsers);
    this.SoftBounces = ko.observable(data.SoftBounces);

    this.TotalRecord = ko.observable(data.TotalRecord);

    this.HasDelivered = ko.computed(function () {
        return (this.TotalDelivered() == "0") ? false : true;
    }, this);
    this.HasReject = ko.computed(function () {
        return (this.TotalRejected() == "0") ? false : true;
    }, this);
    this.HasSpam = ko.computed(function () {
        return (this.SpamComplaints() == "0") ? false : true;
    }, this);
    this.HasHBounce = ko.computed(function () {
        return (this.HardBounces() == "0") ? false : true;
    }, this);
    this.HasUnknown = ko.computed(function () {
        return (this.UnknownUsers() == "0") ? false : true;
    }, this);
    this.HasSBounce = ko.computed(function () {
        return (this.SoftBounces() == "0") ? false : true;
    }, this);

    //************ SORTING *************//
    function SetTHClass(event, colName) {
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc");
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("desc");

        if (viewModel.SortOrder() === "asc") {
            $("#" + colName).children("span").addClass("asc");
        } else {
            $("#" + colName).children("span").addClass("desc");
        }
    }

    function SwitchSortOrder() {
        if (this.SortOrder() === "asc") {
            this.SortOrder("desc");
        } else {
            this.SortOrder("asc");
        }
    }
    this.SwitchSortOrder = SwitchSortOrder;
    // Sort by Colum/Order
    function SetOrder(event, ColName) {

        if (this.ColName() === ColName) {
            this.SwitchSortOrder();
        } else {
            this.ColName(ColName);
            this.SortOrder("asc");
        }
        SetTHClass(event, ColName);

        if (ColName != "") {
            this.ListEmailItems(SortByPropertyName(ko.utils.unwrapObservable(this.ListEmailItems()), ColName, this.SortOrder()));
        }

    }
    this.SetOrder = SetOrder; // Set to an knockout object

    // sort all items
    function SortByPropertyName(items, propertyName, sortOrder) {
        return items.sort(sortProperty(propertyName, sortOrder));
    }
    function sortProperty(property, sortOrder) {
        if (sortOrder == "asc") {
            return function (a, b) {
                if ($.isNumeric(a[property]) && $.isNumeric(b[property])) {
                    return (parseFloat(a[property]) < parseFloat(b[property])) ? -1 : (parseFloat(a[property]) > parseFloat(b[property])) ? 1 : 0;
                }
                else {
                    if (isDateTime(a[property]) && isDateTime(b[property])) {
                        return (parseDateTime(a[property]) < parseDateTime(b[property])) ? -1 : (parseDateTime(a[property]) > parseDateTime(b[property])) ? 1 : 0;
                    } else {
                        return (a[property].toLowerCase() < b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() > b[property].toLowerCase()) ? 1 : 0;
                    }
                }
            }
        }
        else {
            return function (a, b) {
                if ($.isNumeric(a[property]) && $.isNumeric(b[property])) {
                    return (parseFloat(a[property]) > parseFloat(b[property])) ? -1 : (parseFloat(a[property]) < parseFloat(b[property])) ? 1 : 0;
                }
                else {
                    if (isDateTime(a[property]) && isDateTime(b[property])) {
                        return (parseDateTime(a[property]) > parseDateTime(b[property])) ? -1 : (parseDateTime(a[property]) < parseDateTime(b[property])) ? 1 : 0;
                    } else {
                        return (a[property].toLowerCase() > b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() < b[property].toLowerCase()) ? 1 : 0;
                    }
                }

            }
        }
    }

    //************ EVENT *************//
    this.GoButton = function () {
        var tempOpt = $("#SelectTemplates").editableSelect('value');
        var leadSourceOpt = $("#SelectLeadSources").editableSelect('value');
        var emailOpt = $("#SelectEmails").editableSelect('value');
        if (viewModel.RangeOption() == "true") {
            var dataPost = { "templateID": tempOpt,
                "leadsourceID": leadSourceOpt,
                "emailID": emailOpt,
                "rangeID": viewModel.DateSent()
            };
        } else {
            var dataPost = { "templateID": tempOpt,
                "leadsourceID": leadSourceOpt,
                "emailID": emailOpt,
                "startDate": $('#startDate').val(),
                "endDate": $('#endDate').val()
            };
        }

        var urlPost = "/EmailSummary/GetData";
        openProcessBar();

        $.ajax({ type: "POST", url: urlPost, data: dataPost, dataType: "json",
            success: function (returnData, textStatus, jqXHR) {
                //console.log(returnData);
                hideProcessBar();
                if (returnData.Error == undefined || returnData.Error == null) {
                    

                    viewModel.ShowListEmail(false);
                    viewModel.DeliverPercent(FormatPercentOutput(returnData.DeliverPercent));
                    viewModel.RejectPercent(FormatPercentOutput(returnData.RejectPercent));
                    viewModel.SpamPercent(FormatPercentOutput(returnData.SpamPercent));
                    viewModel.hBouncePercent(FormatPercentOutput(returnData.hBouncePercent));
                    viewModel.UnknownUPercent(FormatPercentOutput(returnData.UnknownUPercent));
                    viewModel.sBouncePercent(FormatPercentOutput(returnData.sBouncePercent));

                    viewModel.TotalResults(returnData.TotalResults);

                    viewModel.TotalDelivered(returnData.TotalDelivered);
                    viewModel.TotalRejected(returnData.TotalRejected);
                    viewModel.SpamComplaints(returnData.SpamComplaints);
                    viewModel.HardBounces(returnData.HardBounces);
                    viewModel.UnknownUsers(returnData.UnknownUsers);
                    viewModel.SoftBounces(returnData.SoftBounces);

                    viewModel.ListEmailItems.removeAll();
                }
                else {
                    showPopupError();
                }
            },
            error: function (xhr, status, error) {

                hideProcessBar();
                showPopupError();
            }
        }); // End ajax post
    };

    // Show list emails
    this.RejectClick = function () {
        GetDetailData("emailsrejected");
    }
    this.SpamClick = function () {
        GetDetailData("spamcomplaints");
    }
    this.HBounceClick = function () {
        GetDetailData("hardbounces");
    }
    this.UnknownUClick = function () {
        GetDetailData("unknownusers");
    }
    this.SBounceClick = function () {
        GetDetailData("softbounces");
    }

    function RemoveSortIcons() {
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc");
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("desc");
    }

    function GetDetailData(failureType) {
        var tempOpt = $("#SelectTemplates").editableSelect('value');
        var leadSourceOpt = $("#SelectLeadSources").editableSelect('value');
        var emailOpt = $("#SelectEmails").editableSelect('value');

        if (failureType == "") {
            var dataPost = { "templateID": tempOpt,
                "leadsourceID": leadSourceOpt,
                "emailID": emailOpt,
                "rangeID": viewModel.DateSent()
            };
        }
        else {

            if (viewModel.RangeOption() == "true") {
                var dataPost = { "templateID": tempOpt,
                    "leadsourceID": leadSourceOpt,
                    "emailID": emailOpt,
                    "rangeID": viewModel.DateSent(),
                    "failureType": failureType
                };
            } else {
                var dataPost = { "templateID": tempOpt,
                    "leadsourceID": leadSourceOpt,
                    "emailID": emailOpt,
                    "startDate": $('#startDate').val(),
                    "endDate": $('#endDate').val(),
                    "failureType": failureType
                };
            }
        }


        var urlPost = "/EmailSummary/GetDataDetail";
        openProcessBar();

        $.ajax({ type: "POST", url: urlPost, data: dataPost, dataType: "json",
            success: function (returnData, textStatus, jqXHR) {
                hideProcessBar();
                if (returnData.Error == undefined || returnData.Error == null) {
                    if ((returnData.listEmailitem != "") && (returnData.listEmailitem != null)) {
                        viewModel.CurrentPageIndex(1);
                        viewModel.ListEmailItems(returnData.listEmailitem);
                        viewModel.EmailRecords(returnData.listEmailitem.length);
                        //console.log(returnData.listEmailitem);

                        // Update list
                        viewModel.ShowListEmail(true);
                        RemoveSortIcons();
                        switch (failureType) {
                            case ("emailsrejected"):
                                viewModel.EmailType("Emails Rejected");
                                break;
                            case ("spamcomplaints"):
                                viewModel.EmailType("Spam Complaints");
                                break;
                            case ("hardbounces"):
                                viewModel.EmailType("Hard Bounces");
                                break;
                            case ("unknownusers"):
                                viewModel.EmailType("Unknown Users");
                                break;
                            case ("softbounces"):
                                viewModel.EmailType("Soft Bounces");
                                break;
                        }
                    }
                    else {
                        //console.log(returnData);
                    }

                }
                else {
                    showPopupError();
                }
            },
            error: function (xhr, status, error) {

                hideProcessBar();
                showPopupError();
            }
        }); // End ajax post
    }

    ///////////////////// Paging /////////////////////////////
    this.PreviousPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            this.CurrentPageIndex(page - 1);
        }
    }
    this.NextPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page < this.MaxPageIndex()) {
            this.CurrentPageIndex(page + 1);
        }
    }

    // PageSize/ PageCurrent keypress enter
    this.RunSomethingKey = function (viewModel, event) {
        if (event.keyCode == 13) {
            this.RunSomething(viewModel, event);
        }
        return true;
    }

    this.RunSomething = function (viewModel, event) {
        return true;
        LoadDataKeyPresss();
    }

    function LoadDataKeyPresss() {
        // Page Size
        var pageSizeValue = $('#pagesize').val().toString().replace(/\s/g, '');
        var pagesize = parseInt(pageSizeValue, 10);
        if (!IsNumeric(pageSizeValue) || pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
            return false;
        }

        // Page Index
        var pageIndexValue = $('#pagecurrent').val().toString().replace(/\s/g, '');
        var pageindex = parseInt(pageIndexValue, 10);
        if (!IsNumeric(pageIndexValue) || pageindex.toString() == 'NaN' || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
            return false;
        }
    }

    //************ CLASS FORMAT *************//
    this.DeliveredClass = ko.computed(function () {
        return (this.DeliverPercent() == '0') ? "div-visibility-hide" : "linelink div-visibility-show";
    }, this);

    this.RejectedClass = ko.computed(function () {
        return (this.RejectPercent() == '0') ? "div-visibility-hide" : "linelink div-visibility-show";
    }, this);

    this.SpamClass = ko.computed(function () {
        return (this.SpamPercent() == '0') ? "div-visibility-hide" : "linelink div-visibility-show";
    }, this);

    this.hBounceClass = ko.computed(function () {
        return (this.hBouncePercent() == '0') ? "div-visibility-hide" : "linelink div-visibility-show";
    }, this);

    this.UnknownUClass = ko.computed(function () {
        return (this.UnknownUPercent() == '0') ? "div-visibility-hide" : "linelink div-visibility-show";
    }, this);

    this.sBounceClass = ko.computed(function () {
        return (this.sBouncePercent() == '0') ? "div-visibility-hide" : "linelink div-visibility-show";
    }, this);

    this.ListEmailClass = ko.computed(function () {
        return (this.ShowListEmail()) ? "div-show" : "div-hide";
    }, this);

    this.PagingClass = ko.computed(function () {
        /*if (!isNaN(this.EmailRecords())) {
        return (parseInt(this.EmailRecords()) > 100) ? "paging div-show" : "div-hide";
        }*/
        return "paging div-show";
    }, this);

    // Paging
    this.PrevButtonClass = ko.computed(function () {
        var page = parseInt(this.CurrentPageIndex());
        return (page > 1) ? "btn btn-prev-arrow prev-active" : "btn btn-prev-arrow";
    }, this);

    this.NextButtonClass = ko.computed(function () {
        if (this.CurrentPageIndex() == this.MaxPageIndex() || this.MaxPageIndex() == 1)
            return "btn btn-next-arrow next-disabled";
        else
            return "btn btn-next-arrow";
    }, this);
};

ko.applyBindings(viewModel, document.getElementById('viewEmailSummary'));

// Fire event when datetime inputbox lost focus
// Set CurrentDatetime for it
$('#startDate').blur(function () {
    setTimeout(function () {
        if (!isDateUS($('#startDate').val())) {
            $('#startDate').val(getCurrentDate());
        }
    }, 1);
});

$('#endDate').blur(function () {
    setTimeout(function () {
        if (!isDateUS($('#endDate').val())) {
            $('#endDate').val(getCurrentDate());
        }
    }, 1);
});

//************ PRIVATE METHOD *************//
//Format percent output method
function FormatPercentOutput(percentInput) {
    if (percentInput != "0") {
        return percentInput + "%";
    } else {
        return percentInput;
    }
}

//Format percent output method
function FormatNumOutput(numberInput) {
    return "(" + numberInput + ")";
}

$(document).ready(function () {
    // Change combobox item color to black
    $("div#selectDataHolder").find(".jcf-unselectable").children("span").css('color', '#000000');
        
    $('#SelectEmails').focus(function() {
        $(this).css("outline", "none");
    });
    $('#SelectLeadSources').focus(function () {
        $(this).css("outline", "none");
    });
    $('#SelectTemplates').focus(function () {
        $(this).css("outline", "none");
    });

});

// Progress Bar
function openProcessBar() {
    $.fancybox($('#popup-process'), {
        padding: 0,
        closeBtn: false,
        helpers: {
            overlay: {
                opacity: 0.6,
                css: {
                    'background-color': '#11619D'
                }
            }
        },
        beforeClose: function () {
            return false;
        }
    });
    $('.fancybox-skin').show();
    $('#fancybox-overlay').show();
}
function hideProcessBar() {
    $('#popup-process').hide();
    $('.fancybox-skin').hide();
    $('#fancybox-overlay').hide();
}